#include "LinkedList.h" 
#include <stdlib.h>

// Create a new list linkedList and returns a pointer to it.
struct linkedList* createList()
{
	struct linkedList* newList = (struct linkedList*)malloc(sizeof(struct linkedList));

	newList->length = 0;
	newList->head = NULL; // ensue the next node is null since were adding at the end.

	return newList;
}

// Creates a new node and returns a pointer to it.
struct node* createNode(int data)
{
	struct node* newNode = (struct node*)malloc(sizeof(struct node));

	newNode->data = data;
	newNode->next = NULL; // ensue the next node is null since were adding at the end.

	return newNode;
}

// Adds the given node to the beginning of the given list. Replaces the head.
void addToStartOfList(struct linkedList** listRef, int data)
{
	struct linkedList* localList = *listRef;
	struct node* localHead = localList->head;
	struct node* oldHead = localHead;

	localHead = createNode(data);
	localHead->next = oldHead;

	localList->head = localHead;

	localList->length++;
}

// Adds the given node to the end of the given list.
void addToEndOfList(struct linkedList** listRef, int data)
{
	struct linkedList* localList = *listRef;
	struct node* localHead = localList->head;

	struct node* current = localHead;
	struct node* prevoius = NULL;

	while (current != NULL)
	{
		prevoius = current;
		current = current->next;
	}

	if(prevoius == NULL)
	{
		localList->head = createNode(data); // this will be the head element.
	} 
	else
	{
		prevoius->next = createNode(data);
	}

	localList->length++;
}

void bubbleSort(struct linkedList** listRef)
{
	struct linkedList* localList = *listRef;
	struct node* localHead = localList->head;

	struct node* next = NULL;
	struct node* curr = localList->head;
	
	int len = localList->length;

	int i;
	for (i = 0; i < len; i++)
	{
		curr = localHead;
		while (curr->next != NULL)
		{
			next = curr->next;

			if (curr->data > next->data)
			{
				// this moves the node data rather than the node itself. Sub optimal.
				int temp = curr->data;
				curr->data = next->data;
				next->data = temp;
			}

			curr = curr->next;
		}
	}
}
